#include "mat_level_manager.h"
#include "mat_leveldata.h"
#include "mat_ui_popupanimator.h"
#include "mat_gamerule.h"
#include "gen_game_state.h"
#include "mat_animation_mgr.h"
#include "mat_scoring.h"
#include "mat_sfx_manager.h"
#include "mat_ui_msgbox.h"
#include "build.h"

#include "nextpeer/np_manager.h"
#include "gameflow/ui_popup.h"
#include "application/game_application.h"
#include "application/game_rms.h"
#include "ui/ui_progress.h"
#include "lang/lang.h"
#include "ui/ui_manager.h"
#include "ui/ui_part2dwidget.h"
#include "num/rand.h"
#include "script/scripthelper.h"

#include "util/mmgr.h"		    // Needs to come in early
#include "util/common_macros.h"		// macros
#include "util/log.h"		    // logging
#include <cassert>



MATLevelManager&	MATLevelManager::Instance()
{
	static	MATLevelManager	Inst;
	return Inst;
}

MATLevelManager::~MATLevelManager()
{
	UTIL_SAFE_DELETE(m_pTargetGem1);
	UTIL_SAFE_DELETE(m_pTargetGem2);
}

MATLevelManager::MATLevelManager() : m_pCurrentData(NULL),
									 m_MoveCount(0),
									 m_RemainingMove(1),
									 m_DealyGameOver(0),
									 m_State(STATE_PLAYING),
									 m_NextGemClearDelay(0),
									 m_RemainingTime(0),
									 m_BombExplodeDelay(0),
									 m_IsBombExploded(false),
									 m_pMsgPopup(NULL),
									 m_CurrentLevelIndex(-1),
									 m_LevelFailPopupDelay(0)
{
	
	m_pUIReMainingMove = ui::UIManager::Instance().GetWidget("move");
	m_pUIScoreTarget = ui::UIManager::Instance().GetWidget("pos_target");
	m_pUIPart2dMoveLow = (ui::UIPart2DWidget*)ui::UIManager::Instance().GetWidget("part2d_move_low");
	m_pUIRemainingTime = ui::UIManager::Instance().GetWidget("time_remaining");
	m_pUITimeFrame = ui::UIManager::Instance().GetWidget("time");
	m_pUIProgressTime = (ui::UIProgress*)ui::UIManager::Instance().GetWidget("progress_time");

	m_pUIGemModeFrame = ui::UIManager::Instance().GetWidget("gemmode");
	m_pUIScoreModeFrame = ui::UIManager::Instance().GetWidget("pos_target");
	m_pUIGemTarget1 = ui::UIManager::Instance().GetWidget("gem_1");
	m_pUIGemTarget2  = ui::UIManager::Instance().GetWidget("gem_2");
	m_pUIGemTargetTxt1  = ui::UIManager::Instance().GetWidget("gem_count_1");
	m_pUIGemTargetTxt2  = ui::UIManager::Instance().GetWidget("gem_count_2");

	char Buffer[256];		
	for(int i = 0; i < 3; i++)
	{
		sprintf(Buffer, "star%i", i+1);
		m_pUIStarsPoint[i] = ui::UIManager::Instance().GetWidget(Buffer);
		
	}

	ui::UIWidget* pWidget = ui::UIManager::Instance().GetWidget("progress_score");
	if(pWidget)
		m_ProgressWidth = pWidget->GetSize().x;

	
	
}

int		MATLevelManager::GetCurrentLevel()
{
	if(m_pCurrentData)
		return m_pCurrentData->Index;

	return 1;
}




bool			MATLevelManager::IsLevelSuccess()
{
	if(!m_pCurrentData)
		return false;
	
	if(m_IsBombExploded)
	{
		m_FailReason = "LOC_BOMB_EXPLODE";
		return false;
	}
	
	int Score = MATScoring::Instance().GetScoreValue();

	if(MATLogicBoard::Instance().IsAllBig())
	{
		m_FailReason = "LOC_NO_MOREMOVE";
		return false;
	}
	if(Score < m_pCurrentData->Score[0])
	{
		m_FailReason = "LOC_DIDNOT_TARGET";
		return false;
	}

	else if( IsModeTileClear() && !MATLogicBoard::Instance().IsAllTileClear()
		)
	{
		m_FailReason = "LOC_DIDNOT_CLEAR";
		return false;
		
	}
	else if( IsModeTimeOut() && m_RemainingTime <= 0 && Score < m_pCurrentData->Score[0]  )
	{
		m_FailReason = "LOC_TIMEUP";
		return false;
	}

	else if(m_pCurrentData->m_GameType == GAMETYPE_REACH_MOVECOUNT)
	{
		m_FailReason = "LOC_DIDNOTMOVE";
		return false;
	}
	else if( IsModeGem() &&
		( m_CountTargetGem1 < m_pCurrentData->Gem1Count || m_CountTargetGem2 < m_pCurrentData->Gem2Count ))
	{
		m_FailReason = "LOC_NOTENOUGHGEM";
		return false;
	}

	return true;
}
	
int				MATLevelManager::GetStarCount()
{
	if(m_pCurrentData && IsLevelSuccess())
	{
		int Score = MATScoring::Instance().GetScoreValue();

		for(int i = 2; i >=0; i--)
			if(Score >= m_pCurrentData->Score[i])
			return i+1;


	}
	return 0;
}


void			MATLevelManager::Tick(float dt)
{
	m_ClearGem.Tick(dt);
	if(IsModeTimeOut())
	{
		if(m_RemainingTime > 0)
		{
			if(m_pMsgPopup)
			{
				if(!m_pMsgPopup->IsActive())
				{
					m_RemainingTime-= dt;
					if(m_RemainingTime <= 0)		
						m_State = STATE_ABOUTTOEND;
				
					if(m_pUIProgressTime)
					{
						const float V = m_RemainingTime / (float)m_pCurrentData->Time;
						m_pUIProgressTime->SetProgress(V);
					}
				}
				
			}
			else
			{
				MATUIPopupAnimator* pPopupAnimator = MATUIPopupAnimatorMgr::Instance().GetPopup(MATUIPopupAnimatorMgr::POPUP_NAMES_MSGBOX);
				m_pMsgPopup = pPopupAnimator->GetPopup();					  
			}

			
		}


		if(m_pUIRemainingTime)
		{
			char Buffer[256];
			int Minute = ((int)m_RemainingTime) / 60;
			int Sec = ((int)m_RemainingTime) % 60;

			sprintf(Buffer, "%02i:%02i", Minute, Sec);

			m_pUIRemainingTime->SetTextA(Buffer);
		}
	}

	m_ComboLevelComplete.Tick(dt);

	switch( m_State)
	{

	case STATE_PLAYING:
		break;

	case STATE_EXTRAMOVE_CLEARING:


		if(  (!IsModeTimeOut() && (MATLogicBoard::Instance().IsEmpty() || m_RemainingMove <= 0)) ||
			(IsModeTimeOut() && m_RemainingTime <= 0 )

			)
		{
			m_State = STATE_ABOUTTOEND;
			
		}
		else
		{
			m_ExtraMoveClearing.Tick(dt);

			if(m_NextGemClearDelay > 0)
			{
				m_NextGemClearDelay -= dt;
			}

			if(m_NextGemClearDelay <= 0)
			{
				m_ExtraMoveClearing.ClearRandomGem();
				
				m_NextGemClearDelay = 0.25f;

				if(!IsModeTimeOut())
				{
					m_RemainingMove --;	
					if(m_RemainingMove < 0)
						m_RemainingMove = 0;

				}
				else
				{
					m_RemainingTime -= 5.0f;
					if(m_RemainingTime <= 5.0f)
						m_RemainingTime = 0;
				}


				if(m_pUIReMainingMove)
					m_pUIReMainingMove->SetTextA( lang::Lang::FormatNumber(m_RemainingMove ));
			}
		}
		break;
	case STATE_BOMBEXPLODE:
		m_IsBombExploded = true;
		m_BombExplodeDelay = 1.0f;
		m_State = STATE_BOMBEXPLODING;
		m_ClearGem.Init(false);
		MATLogicBoard::Instance().Clear();
		break;
	
	case STATE_BOMBEXPLODING:
		if( m_BombExplodeDelay > 0) 
		{
			m_BombExplodeDelay -= dt;
			if( m_BombExplodeDelay <= 0)
			{
				m_State = STATE_ABOUTTOEND;
				
			}
		}
		break;
	case STATE_ABOUTTOEND:
		m_ExtraMoveClearing.Tick(dt);
		if(m_ExtraMoveClearing.IsAllFinish())
		{
			float COMBODELAY = MATScoring::Instance().GetComboShowingTime();
			if(COMBODELAY > 0)
				COMBODELAY += 0.2f;
			
			m_ComboLevelComplete.Show( (MATLevelCompletePopup::STATE_LEVEL)IsLevelSuccess(), 
										0.1f + COMBODELAY , 
										1.25f);

			m_State = STATE_BOARDANIMATE;
			
			if(!IsLevelSuccess())			
				m_LevelFailPopupDelay = 1.25f + COMBODELAY;
		}
		break;
	case STATE_BOARDANIMATE:
		if(IsLevelSuccess())
		{
			float COMBODELAY = MATScoring::Instance().GetComboShowingTime();
			if(COMBODELAY > 0)
				COMBODELAY += 0.2f;

			GENGameState::GetGame()->GetGameMatch5()->AnimateHideBoard(1.5f + COMBODELAY);		
			m_State = STATE_BOARDANIMATING;
			m_BoardAnimateDelay = 1.25f;
			m_BoardAnimateDelay += COMBODELAY;

		}
		else
		{
			if(m_LevelFailPopupDelay > 0)
			{
				m_LevelFailPopupDelay -= dt;
			}
			else
			{
				m_State = STATE_ENDING;
			}
		}
		break;

	case STATE_BOARDANIMATING:
		m_BoardAnimateDelay -= dt;
		if( m_BoardAnimateDelay <= 0)
		{
			m_State = STATE_ENDING;
			m_DealyGameOver = 1.5f;
		}
		break;

	case STATE_ENDING:
			
		m_DealyGameOver -= dt;
		if(m_DealyGameOver <= 0)
		{		

			MATUIPopupAnimatorMgr::Instance().Show(MATUIPopupAnimatorMgr::POPUP_NAMES_GAMEOVER);			
			m_State = STATE_AFTEREND;
		}
		
	case STATE_AFTEREND:

		break;
	}
	
}

bool	MATLevelManager::ShouldSpawnMoreBombs() const
{
	if(!m_pCurrentData)
		return false;

	return m_pCurrentData->m_ToSpawnMoreBomb;
}
	
void			MATLevelManager::AddMatched(const std::vector<MATGem*>& List)
{
	bool IsGemGot1 = false;
	bool IsGemGot2 = false;

	MATGem* pBC;
	for(int i =0; i < (int)List.size(); i++)
	{
		if(IsModeTimeOut() && List[i]->m_IsTimeBonus)
		{
			m_RemainingTime += 5;					
		}
		
		if(IsModeGem())
		{
			pBC = List[i];

			if(pBC->m_Type == m_pTargetGem1->m_Type)
			{
				m_CountTargetGem1++;
				IsGemGot1 = true;
			}

			else if(pBC->m_Type == m_pTargetGem2->m_Type)
			{
				m_CountTargetGem2++;
				IsGemGot2 = true;
			}

			if(m_CountTargetGem1 > m_pCurrentData->Gem1Count)
				m_CountTargetGem1 = m_pCurrentData->Gem1Count;

			if(m_CountTargetGem2 > m_pCurrentData->Gem2Count)
				m_CountTargetGem2 = m_pCurrentData->Gem2Count;
		}
	}
	
	UpdateTargetGemUI();

	if(IsGemGot1)
		MATUIAnimator::Instance().Add(	m_pUIGemTarget1,
									MATAnimatedUI::ANIMATE_STYLE_POPPINGUP,
									0.0f,NULL);

	if(IsGemGot2)
		MATUIAnimator::Instance().Add(	m_pUIGemTarget2,
									MATAnimatedUI::ANIMATE_STYLE_POPPINGUP,
									0.0f,NULL);

	//CheckLevelComplete();
}

void			MATLevelManager::NextMove()
{
	if(IsModeMove())
	{
		m_RemainingMove--;
		if(m_pUIReMainingMove)
			m_pUIReMainingMove->SetTextA( lang::Lang::FormatNumber(m_RemainingMove ));

		if(m_pUIPart2dMoveLow && m_RemainingMove <= 5 && IsModeMove())
			m_pUIPart2dMoveLow->SetIsVisible(true);
	}

	m_MoveCount++;
	
	CheckLevelComplete();

	
}

void			MATLevelManager::CheckLevelComplete()
{
	m_DealyGameOver = 0;	
	if(m_pCurrentData)
	{
		if( IsModeMove() &&
			m_RemainingMove <= 0
			) 	 
		{
			m_DealyGameOver = 1.0f;	
			m_State = STATE_ABOUTTOEND;
		}


		if( IsModeTileClear()  && MATLogicBoard::Instance().IsAllTileClear() )
		{
			m_DealyGameOver = 3.0f;
			m_State = STATE_EXTRAMOVE_CLEARING;
			m_ExtraMoveClearing.Clear();
		}

		if( IsModeGem() &&
			m_CountTargetGem1 >= m_pCurrentData->Gem1Count &&
			m_CountTargetGem2 >= m_pCurrentData->Gem2Count
			)
		{
			m_DealyGameOver = 3.0f;
			m_State = STATE_EXTRAMOVE_CLEARING;
			m_ExtraMoveClearing.Clear();
		}

	}
}

bool			MATLevelManager::IsModeTimeOut() const
{
	if(		m_pCurrentData && 
			(m_pCurrentData->m_GameType == GAMETYPE_CLEAR_TILES_TIMEOUT ||
			 m_pCurrentData->m_GameType == GAMETYPE_GETGEMSTOCOUNT_WITHTIMEOUT||
			 m_pCurrentData->m_GameType == GAMETYPE_SCORE_WITHTIMEOUT)
			)
	{
		return true;
	}

	return false;
}

bool			MATLevelManager::IsModeMove() const
{
	 if(m_pCurrentData&&
		 (m_pCurrentData->m_GameType == GAMETYPE_CLEAR_TILES_WTIHMOVE ||
		 m_pCurrentData->m_GameType == GAMETYPE_GETGEMSTOCOUNT_WITHMOVE||
		 m_pCurrentData->m_GameType == GAMETYPE_SCORE_WITHMOVE)
		)
	 {
		 return true;
	 }
	 return false;
}

bool			MATLevelManager::IsModeTileClear() const
{
	  if(	m_pCurrentData&&
		   (m_pCurrentData->m_GameType == GAMETYPE_CLEAR_TILES_TIMEOUT ||
			m_pCurrentData->m_GameType == GAMETYPE_CLEAR_TILES_WTIHMOVE)
		)
	 {
		 return true;
	 }
	 return false;
}

void			MATLevelManager::Render(float Scale)
{
	m_ClearGem.Render();
	m_ComboLevelComplete.Render();
	m_ExtraMoveClearing.Render(Scale);
}

void			MATLevelManager::SetCurrentLevel(int Index, bool LauchNextPeerDashBoard = true)
{	
	if(LauchNextPeerDashBoard)
    {
		NextPeerManager::Instance().SetCurrentTournament(Index);
        NextPeerManager::Instance().SetCurrentTournament(TOURNAMENT_IDS[Index-1]);
    }

	m_CurrentLevelIndex = Index;
	SetMusicTheme();
	

	m_IsBombExploded = false;
	g_pApp->GetRMS()->SetInt(RMS_LASTLEVEL, m_CurrentLevelIndex);

	m_State = STATE_PLAYING;
	MATLogicBoard::Instance().Clear();	

	char Buffer[256];
	sprintf(Buffer, "%i", m_CurrentLevelIndex);
	m_pCurrentData = MATLevelDataSet::Instance().GetLevel(Buffer);

	m_CountTargetGem1 = 0;
	m_CountTargetGem2 = 0;

	if(m_pCurrentData)
	{
		m_RemainingMove = m_pCurrentData->Move;
		m_RemainingTime = (float)m_pCurrentData->Time;

		if(m_pCurrentData->GemTypeCountInGame > 0)
			MATGameRule::Instance().SetCountOfExcludeGemTypes(GEM_UNIQUE_COUNT - m_pCurrentData->GemTypeCountInGame);

		if(m_pUIScoreTarget)
		{
			m_pUIScoreTarget->SetTextA("LOC_TARGET");			
			//sprintf(Buffer, "%s: %s", m_pUIScoreTarget->GetText().c_str(), lang::Lang::FormatNumber( m_pCurrentData->Score[0],true).c_str() );
			std::string Temp = lang::Lang::FormatNumber( m_pCurrentData->Score[0],true);
			std::wstring TempW = lang::Lang::ConvertAtoW(Temp);
			m_pUIScoreTarget->SetTextW(m_pUIScoreTarget->GetText() + TempW );
		}

		if(IsModeTimeOut()
			)
		{
			if(m_pUIReMainingMove)
				m_pUIReMainingMove->SetIsVisible(false);

			if(m_pUITimeFrame)
				m_pUITimeFrame->SetIsVisible(true);

			if(m_pUIProgressTime)
			{
				const float V = m_RemainingTime / (float)m_pCurrentData->Time;
				m_pUIProgressTime->SetProgress(V);
			}
		}
		
		if(IsModeMove())
		{
			if(m_pUIReMainingMove)
			{
				m_pUIReMainingMove->SetTextA( lang::Lang::FormatNumber(m_RemainingMove ));
				m_pUIReMainingMove->SetIsVisible(true);
			}

			if(m_pUITimeFrame)
				m_pUITimeFrame->SetIsVisible(false);				
		}
		
		if(IsModeGem())
		{
			if(m_pUIGemModeFrame)
				m_pUIGemModeFrame->SetIsVisible(true);

			if(m_pUIScoreModeFrame)
				m_pUIScoreModeFrame->SetIsVisible(false);

			m_pTargetGem1 = MATGameRule::Instance().GetNewGemToSpawn();
			
			do
			{
				m_pTargetGem2 = MATGameRule::Instance().GetNewGemToSpawn();
			}
			while(m_pTargetGem1->m_Type == m_pTargetGem2->m_Type);

			m_pTargetGem1->m_IsSmall = false; 
			m_pTargetGem2->m_IsSmall = false; 

			
			
			if(m_pUIGemTarget1)
			{
				sprintf(Buffer, "gem_ui_%i", m_pTargetGem1->m_Type);
				m_pUIGemTarget1->SetOffImage(Buffer);
			}

			if(m_pUIGemTarget2)
			{
				sprintf(Buffer, "gem_ui_%i", m_pTargetGem2->m_Type);
				m_pUIGemTarget2->SetOffImage(Buffer);
			}
			
			UpdateTargetGemUI();
			MATUIAnimator::Instance().Add(	m_pUIGemTarget1,
									MATAnimatedUI::ANIMATE_STYLE_POPPINGUP,
									1.0f,NULL);
			MATUIAnimator::Instance().Add(	m_pUIGemTarget2,
									MATAnimatedUI::ANIMATE_STYLE_POPPINGUP,
									1.5f,NULL);

		}
		else
		{
			if(m_pUIGemModeFrame)
				m_pUIGemModeFrame->SetIsVisible(false);

			if(m_pUIScoreModeFrame)
				m_pUIScoreModeFrame->SetIsVisible(true);
		}

		
		
		sprintf(Buffer, "levels/level_%i.lua", m_pCurrentData->Index );			
		GENGameState::GetGame()->Load(Buffer);
		if(GENGameState::GetGame()->GetGameMatch5())
			GENGameState::GetGame()->GetGameMatch5()->BuildRenderList();


		math::Vec2 TempPos;
		for(int i = 0; i < 3; i++)
		{
			//;
			TempPos.y = m_pUIStarsPoint[i]->GetPositionRelativeToParent().y;

			TempPos.x = m_ProgressWidth;
			TempPos.x *= ( (float)m_pCurrentData->Score[i] / (float)m_pCurrentData->Score[2]  );
			//TempPos.x -=  (m_ProgressWidth * 0.5f);
			if(m_pUIStarsPoint[i])
			{
				m_pUIStarsPoint[i]->SetPositionRelativeToParent(TempPos + m_pUIStarsPoint[i]->GetParent()->GetPosition() );
			}
		}
			
	}	

	ShowLevelInfoMsg();
	SetGameBackground();

	if(m_pUIPart2dMoveLow)
		m_pUIPart2dMoveLow->SetIsVisible(false);	
}

void			MATLevelManager::SetMusicTheme()
{
	if(IsModeTimeOut())
	{
		MATSounds::Instance().PlayMusic("sounds/theme_timesounds.ogg");
	}
	else if(IsModeTileClear())
	{
		MATSounds::Instance().PlayMusic("sounds/theme_tile.ogg");
	}
	else
	{
		MATSounds::Instance().PlayMusic("sounds/theme_score.ogg");
	}
}

void			MATLevelManager::ShowLevelInfoMsg() const
{
	if(!m_pCurrentData)
		return;

	char Buffer[256];

#ifdef _BUILD_CHINESE

	switch (m_pCurrentData->m_GameType)
	{
	case GAMETYPE_SCORE_WITHMOVE:
		sprintf(Buffer, "LOC_GIVENMOVES");
		break;

	case GAMETYPE_SCORE_WITHTIMEOUT:
		sprintf(Buffer, "LOC_GIVENSECONDS");
		break;

	case GAMETYPE_CLEAR_TILES_WTIHMOVE:
		sprintf(Buffer, "LOC_CLEARMOVES");
	break;

	case GAMETYPE_CLEAR_TILES_TIMEOUT:
		sprintf(Buffer, "LOC_CLEARSECONDS");
	break;
	
	case GAMETYPE_GETGEMSTOCOUNT_WITHMOVE:
		sprintf(Buffer, "LOC_COLLECTGEMS");
	break;

	case GAMETYPE_GETGEMSTOCOUNT_WITHTIMEOUT:
		sprintf(Buffer, "LOC_COLLECTSECONDS");
	break;

	}

#else	
	switch (m_pCurrentData->m_GameType)
	{
	case GAMETYPE_SCORE_WITHMOVE:
		sprintf(Buffer, "Get '%i' Points in '%i' Moves.", m_pCurrentData->Score[0] , m_pCurrentData->Move);
		break;
	case GAMETYPE_SCORE_WITHTIMEOUT:
		sprintf(Buffer, "Get '%i' Points in '%i' Seconds.", m_pCurrentData->Score[0] , m_pCurrentData->Time);
		break;
	case GAMETYPE_CLEAR_TILES_WTIHMOVE:
		sprintf(Buffer, "Clear all the 'Tiles' in '%i' Moves.",  m_pCurrentData->Move);
	break;
	case GAMETYPE_CLEAR_TILES_TIMEOUT:
		sprintf(Buffer, "Clear all the 'Tiles' in '%i' Seconds.",  m_pCurrentData->Time);
	break;
	
	case GAMETYPE_GETGEMSTOCOUNT_WITHMOVE:
		sprintf(Buffer, "Collect wanted 'Gems' in '%i' Moves.",  m_pCurrentData->Move);
	break;

	case GAMETYPE_GETGEMSTOCOUNT_WITHTIMEOUT:
		sprintf(Buffer, "Collect wanted 'Gems' in '%i' Seconds.",  m_pCurrentData->Time);
	break;

	}
#endif

	

	MATUIPopupAnimator* pPopup = MATUIPopupAnimatorMgr::Instance().GetPopup(MATUIPopupAnimatorMgr::POPUP_NAMES_MSGBOX);
	((MATUIMsgBox*)pPopup)->ShowExtra(0.2f, Buffer , MATUIMsgBox::ACTION_NONE);
}

void			MATLevelManager::UpdateTargetGemUI()
{
	if(!m_pCurrentData)
		return;

	if(!IsModeGem())
		return;

	char Buffer[256];
	int Temp = m_pCurrentData->Gem1Count;
	sprintf(Buffer, "%i/%i", m_CountTargetGem1,Temp );

	if(m_pUIGemTargetTxt1)
		m_pUIGemTargetTxt1->SetTextA(Buffer);

	Temp = m_pCurrentData->Gem2Count;
	sprintf(Buffer, "%i/%i", m_CountTargetGem2,Temp);

	if(m_pUIGemTargetTxt2)
		m_pUIGemTargetTxt2->SetTextA(Buffer);
}
	
void			MATLevelManager::ReplayLevel()
{
	math::Vec2 TempV;
	// Game Over Gem Clear Effect
	//for(int y = 0; y < MATGameRule::Instance().GetBoardCountY(); y++)
	//{
	//	for(int x = 0; x < MATGameRule::Instance().GetBoardCountX(); x++)
	//	{
	//		MATGem* BC = MATLogicBoard::Instance().GetContentAt(y,x);
	//		if(BC && BC->m_IsSmall == false )
	//		{
	//			// can move
	//			MATAnimation* pAni = MATAnimationManager::Instance().AddAnimation(
	//														y,
	//														x,
	//														BC, 
	//														MATAnimation::ANI_TYPE_MOVING
	//															);
	//		
	//			((MATAniMoving*)pAni)->ClearPositions();		
	//			((MATAniMoving*)pAni)->SetShouldAccelerate(true);
	//			//pAni->SetCallBack(this);
	//			TempV = MATGame::GetBoardPos(y,x);				
	//			((MATAniMoving*)pAni)->AddMovePosition(TempV );
	//			if(num::RAND32::Instance().RandInt(0,1))
	//				TempV.x = 0;
	//			else
	//				TempV.x = 1.0f;
	//			((MATAniMoving*)pAni)->AddMovePosition( TempV);
	//			((MATAniMoving*)pAni)->ToRotate(true);
	//		}

	//	}
	//}

	if(m_pCurrentData)
		NextPeerManager::Instance().SetCurrentTournament(m_pCurrentData->Index);

	m_ClearGem.Init(false);
	MATLogicBoard::Instance().Clear();

	if(m_pCurrentData)
		SetCurrentLevel(m_pCurrentData->Index, false);
}

int				MATLevelManager::GetStarScore(int StarIndex) const
{
	if(StarIndex > 2)
		return 0;

	if(m_pCurrentData)
		return m_pCurrentData->Score[StarIndex];

	return 0;
}
	

bool             MATLevelManager::ShoulSpawnTimeBonus() const
{
	if(IsModeTimeOut())
	{
		if(m_pUIProgressTime && m_pUIProgressTime->GetProgress() <= 0.35f )
			return true;
	}

	return false;
}

bool		MATLevelManager::IsModeGem() const 
{
	 if(	m_pCurrentData&&
		 (m_pCurrentData->m_GameType == GAMETYPE_GETGEMSTOCOUNT_WITHMOVE||
		  m_pCurrentData->m_GameType == GAMETYPE_GETGEMSTOCOUNT_WITHTIMEOUT)
		)
	 {
		 return true;
	 }
	 return false;
}

void		MATLevelManager::SetGameBackground() 
{
	char Buffer[256];
	int BGIndex = GetCurrentLevel()- 1;
	BGIndex /= 20;
	BGIndex += 1;

	
	MATGame* pGame = NULL;
	if(GENGameState::GetGame())
		pGame = GENGameState::GetGame()->GetGameMatch5();

	if(pGame)
	{
		sprintf(Buffer,"bg_ingame_%i", BGIndex);
		pGame->SetBackGround(Buffer);
	}
}